package com.allen.study.domain.utils.security;

import com.allen.study.test_common.exception.CustomRuntimeException;
import com.allen.study.test_common.utils.jwt.JwtUtils;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName: JwtAuthenticationFilter
 * @Author: AllenSun
 * @Date: 2025/3/7 20:39
 *
 * 从请求头中提取 JWT，验证其有效性，并将用户信息设置到 Spring Security 的上下文当中。
 *
 */
@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    // 注入 JwtUtils
    @Autowired
    private JwtUtils jwtUtils;

    // 注入 UserDetailsService
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 获取请求头中的 Authorization 字段
        log.info("JWT过滤器：开始");
        final String authorizationHeader = request.getHeader("Authorization");

        String username = null;
        String jwt = null;

        // 如果 Authorization 字段不为空且以 Bearer 开头
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            // 获取 JWT
            jwt = authorizationHeader.substring(7);
            try {
                // 从 JWT 中提取用户名
                username = jwtUtils.extractUsername(jwt);
                log.info("JWT过滤器：解析token得到用户名：{}",username);
            } catch (ExpiredJwtException e) {
                // 处理 JWT 过期的情况
                log.info("JWT过滤器：JWT 已过期，请重新登录");
                throw new CustomRuntimeException("JWT 已过期，请重新登录");
            }
        }

        // 如果用户名不为空且 SecurityContextHolder 中没有认证信息
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 从 UserDetailsService 中加载用户信息
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            // 验证 JWT 是否有效
            if (jwtUtils.validateToken(jwt, userDetails)) {
                // 创建 UsernamePasswordAuthenticationToken 对象
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                // 设置认证信息
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // 将认证信息放入 SecurityContextHolder 中
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        // 继续执行过滤器链
        filterChain.doFilter(request, response);
    }
}
